package org.openschool.controller;

import org.openschool.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.openschool.domain.*;

import java.util.*;

import javax.validation.Valid;

@Controller
public class UsersController {

	@Autowired
	private UsersService usersService;

	@RequestMapping("/welcome")
	public String listUsers(ModelMap model){
		model.addAttribute("user",new User());
		List<User> users = usersService.listUsers();
		model.addAttribute("usersList",users);
		return "welcome";
	}
	
 	@RequestMapping(value = "/adduser", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("user") @Valid User user, BindingResult result) {
 		if (result.hasErrors()) {
			System.out.println(result);
			return "users";
 		}
 		usersService.addUser(user);
        return "redirect:/users";
    }
 
    @RequestMapping("/delete/{username}")
    public String deleteContact(@PathVariable("username")
    String username) {
    	usersService.removeUser(username);
        return "redirect:/users";
    }
}
